import Vue from 'vue'

import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
		// 科目列表
		subjectlist: [],
		// 分析页面对于的题目
		questions: [],
		answers: [],
		// 错题记录的是 questions中的数组序号
		errorindexs: [],
		// 历史做题记录
		historylist: null,
		// 错题列表
		wronglist: null,
		// 收藏列表
		collectlist: null,
		// 用户信息
		userInfo: null,

	},
    mutations: {
		setquestions(state, questions){
			state.questions = questions
		},
		setanswers(state, answers){
			state.answers = answers
		},
		seterrorindexs(state, errorindexs){
			state.errorindexs = errorindexs
		},
		setwronglist(state, item){
			state.wronglist = item
		},
		setuserInfo(state, item){
			state.userInfo = item
		},
		sethistorylist(state, item) {
			state.historylist = item
		},
		setcollectlist(state, item) {
			state.collectlist = item
		},
		setcollectitem(state, item) {
			let arr = JSON.parse(JSON.stringify(state.collectlist)) || [] 
			let index = -1
			for (let i=0; i<arr.length; i++) {
				if (arr[i].foldername == item.foldername) {
					index = i
					break
				}
			}
			if (index != -1) {
				// 删除收藏
				if (item.questionIds.length == 0) {
					arr.splice(index, 1)
				} else {
					arr[index] = item
				}
			} else {
				// 添加收藏夹
				arr.push(item)
			}
			// console.log(arr)
			state.collectlist = arr
		},
		delcollectitem(state, item) {
			let arr = JSON.parse(JSON.stringify(state.collectlist)) || [] 
			for (let i=0; i<arr.length; i++) {
				if (arr[i].foldername == item.foldername) {
					arr.splice(i, 1)
					break
				}
			}
			state.collectlist = arr
		},
	},
    actions: {
		//相当于异步的操作,不能直接改变state的值，只能通过触发mutations的方法才能改变
		setanswers(context, item){
			context.commit('setanswers', item);
		},
		setquestions(context, questions){
			context.commit('setquestions', questions);
		},
		setanswers(context, answers){
			context.commit('setanswers', answers);
		},
		seterrorindexs(context, errorindexs){
			context.commit('seterrorindexs', errorindexs);
		},
		setwronglist(context, item){
			context.commit('setwronglist', item);
		},
		setuserInfo(context, item){
			context.commit('setuserInfo', item);
		},
		sethistorylist(context, item){
			context.commit('sethistorylist', item);
		},
		setcollectlist(context, item){
			context.commit('setcollectlist', item);
		},
		setcollectitem(context, item){
			context.commit('setcollectitem', item);
		},
		delcollectitem(context, item){
			context.commit('delcollectitem', item);
		},
	}
})
export default store
